package com.css.dzj.dzjap.modules.lawenforcesuper.service.impl;

import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.RandomUtil;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.*;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.GeneralRelationMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.GenralMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.service.GeneralService;
import com.css.dzj.dzjap.modules.lawenforcesuper.view.GeneralExtractVo;
import com.css.dzj.dzjap.modules.lawenforcesuper.view.GeneralQueryVo;
import com.css.dzj.dzjap.modules.lawenforcesuper.view.GeneralVo;
import com.css.dzj.dzjap.modules.project.generecord.entity.Generecord;
import com.css.dzj.dzjap.modules.project.generecord.service.GenerecordService;
import com.css.dzj.dzjap.modules.publick.dao.PublicDao;
import com.css.dzj.dzjap.modules.publick.entity.ApPublicEntity;
import com.css.dzj.dzjap.modules.todolist.entity.ApTodoEntity;
import com.css.dzj.dzjap.modules.todolist.service.ApTodoService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class GenralServiceImp implements GeneralService {

    @Autowired
    private ServiceUtil serviceUtil;
    @Autowired
    GenerecordService generecordService;
    @Autowired
    GenralMapper genralMapper;
    @Autowired
    GeneralRelationMapper generalRelationMapper;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    // 公开公告Dao
    @Autowired
    private PublicDao publicDao;
    @Autowired
    private ApTodoService apTodoService;
    @Override
    public R saveGeneral(GeneralVo generalVo, HttpServletRequest request) {
        try {
            if(StringUtils.isEmpty(generalVo)){
                throw new RuntimeException("新增不能为空");
            }
            /**
             * 获取suser
             */
            R r = serviceUtil.getUserInfoByRequest(request);
            String suserName = "";
            String location = "";
            String address="";
            String userUnit ="";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                /**
                 * 获取用户名
                 */
                suserName =userInfo.getLoginName();
                /**
                 * 获取用户的省份
                 */
                String orgName = userInfo.getOrgName();
                location = orgName.replace("地震局","");
                address = userInfo.getAddress();
                userUnit= userInfo.getOrgName();
            }
            /**
             * 获取前台传回来的信息
             */
            GeneralWorkInfoEntity generalWorkInfoEntity=generalVo.getGeneralWorkInfoEntity();
            List<GeneralWorkInfoEntity> list=generalVo.getGeneralWorkInfoEntityList();
            GeneralWorkInfoEntity generalWorkInfo;
            List<GeneralWorkInfoEntity> generalWorkInfoEntities=new ArrayList<>();
            GeneralExtractRelationEntity generalExtractRelation;
            List<GeneralExtractRelationEntity> generalExtractRelationEntities=new ArrayList<>();
            String taskId=UUID.randomUUID().toString();
            if(!StringUtils.isEmpty(generalWorkInfoEntity)){
                if(list.size()!=0&&!StringUtils.isEmpty(list)){
                    Date date=new Date();
                    for(GeneralWorkInfoEntity gen:list) {
                        List<Generecord> generecordList=generecordService.getByIn(location,gen.getIndustryNature());
                        Integer num=gen.getExtratNum();
                        String id;
                        if(generecordList.size()<num){
                            throw new RuntimeException("行业性质为"+gen.getIndustryNature()+"数量不够"+num);
                        }else {
                            generalWorkInfo=new GeneralWorkInfoEntity();
                            generalWorkInfo.setId(UUID.randomUUID().toString());
                            generalWorkInfo.setCreatePerson(suserName);
                            generalWorkInfo.setCreatePersonLocation(location);
                            generalWorkInfo.setExtratNum(num);
                            generalWorkInfo.setIndustryNature(gen.getIndustryNature());
                            generalWorkInfo.setTaskId(taskId);
                            generalWorkInfo.setTaskContent(generalWorkInfoEntity.getTaskContent());
                            generalWorkInfo.setEnterpriseNotice("0");
                            generalWorkInfo.setRemarks(generalWorkInfoEntity.getRemarks());
                            generalWorkInfo.setTaskTitle(generalWorkInfoEntity.getTaskTitle());
                            generalWorkInfo.setCreateTime(date);
                            generalWorkInfoEntities.add(generalWorkInfo);
                            List<Generecord> drawList= RandomUtil.ramdonExtract(generecordList,num.toString());
                            for (Generecord draw:drawList) {
                                generalExtractRelation=new GeneralExtractRelationEntity();
                                generalExtractRelation.setGeneralId(draw.getReId());
                                generalExtractRelation.setTaskId(taskId);
                                generalExtractRelation.setCqStatus("0");
                                generalExtractRelation.setCreateTime(new Date());
                                generalExtractRelation.setCreatePerson(suserName);
                                generalExtractRelationEntities.add(generalExtractRelation);
                            }
                        }
                    }
                    genralMapper.saveAll(generalWorkInfoEntities);
                    generalRelationMapper.saveAll(generalExtractRelationEntities);
                    return R.ok("抽取成功").put("taskId", taskId);
                }else {
                    throw new RuntimeException("抽取数量不能为空");
                }
            }else {
                throw new RuntimeException("抽取信息不能为空");
            }
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }

    /***
     * 查看任务列表
     * @param pageable
     * @param title
     * @param request
     * @return
     */
    @Override
    public QueryResults<GeneralWorkInfoEntity> getpage(Pageable pageable, String title, HttpServletRequest request) {
        QGeneralWorkInfoEntity q= QGeneralWorkInfoEntity.generalWorkInfoEntity;
        R r = serviceUtil.getUserInfoByRequest(request);
        String location = "";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            String orgName = userInfo.getOrgName();
            location = orgName.replace("地震局","");
        }
        Page<GeneralWorkInfoEntity> page;
        if (Constant.LOCATIONZG.equals(location)){
            page = genralMapper.getTaskId(title,pageable);
        }else {
            page=genralMapper.getTaskIdByLocation(title,location,pageable);
        }

        List<GeneralWorkInfoEntity> idList=page.getContent();
        List<List> taskList=new ArrayList<>();
        List<GeneralWorkInfoEntity> task;
        for (Object id:idList) {
            Object[] ob=(Object[])id;
            GeneralWorkInfoEntity entity=new GeneralWorkInfoEntity();
            entity.setTaskId(ob[0].toString());
            Predicate predicate=q.isNotNull().or(q.isNull());
            predicate = (title == null || title.isEmpty()) ? predicate : ExpressionUtils.and(predicate, q.taskTitle.like("%" + title + "%"));
            predicate = ExpressionUtils.and(predicate, q.taskId.eq(entity.getTaskId()));
            if (Constant.LOCATIONZG.equals(location)) {
                task = jpaQueryFactory.selectFrom(q).where(predicate).fetch();
            }else {
                predicate = ExpressionUtils.and(predicate, q.createPersonLocation.eq(location));
                task = jpaQueryFactory.selectFrom(q).where(predicate).fetch();
            }
            taskList.add(task);
        }
        List<GeneralWorkInfoEntity> listEntiy=new ArrayList<>();
        for (List li:taskList){
            GeneralWorkInfoEntity generalWorkInfo=new GeneralWorkInfoEntity();
            StringBuffer sb = new StringBuffer();
            int num=0;
            for (int i=0;i<=li.size()-1;i++) {
                GeneralWorkInfoEntity generalWorkInfoEntity=(GeneralWorkInfoEntity)li.get(i);
                generalWorkInfo.setTaskTitle(generalWorkInfoEntity.getTaskTitle());
                generalWorkInfo.setCreateTime(generalWorkInfoEntity.getCreateTime());
                generalWorkInfo.setCreatePerson(generalWorkInfoEntity.getCreatePerson());
                generalWorkInfo.setTaskId(generalWorkInfoEntity.getTaskId());
                generalWorkInfo.setEnterpriseNotice(generalWorkInfoEntity.getEnterpriseNotice());
                generalWorkInfo.setCreatePersonLocation(generalWorkInfoEntity.getCreatePersonLocation());
                sb.append(generalWorkInfoEntity.getIndustryNature());
                sb.append("，");
                num+=generalWorkInfoEntity.getExtratNum();
            }
            if(li.size()>0) {
                sb.delete(sb.length() - 1, sb.length());
                generalWorkInfo.setIndustryNature(sb.toString());
                generalWorkInfo.setExtratNum(num);
                listEntiy.add(generalWorkInfo);
            }
        }

        QueryResults<GeneralWorkInfoEntity> results=new QueryResults<GeneralWorkInfoEntity>(listEntiy,page.getTotalElements(),page.getPageable().getOffset(),page.getTotalElements());
        return results;
    }

    /**
     * 查询关联表信息
     * @param taskId
     * @param pageable
     * @return
     */
    @Override
    public QueryResults<GeneralExtractRelationEntity> queryRelationById(String taskId, Pageable pageable) {
        QGeneralExtractRelationEntity qGeneralExtractRelationEntity=QGeneralExtractRelationEntity.generalExtractRelationEntity;
        return jpaQueryFactory.selectFrom(qGeneralExtractRelationEntity).
                where(qGeneralExtractRelationEntity.taskId.eq(taskId)).
                limit(pageable.getPageSize()).offset(pageable.getOffset()).fetchResults();
    }

    @Override
    public QueryResults<GeneralExtractVo> queryById(String taskId, Pageable pageRequest) {
        if (taskId!=null && !"".equals(taskId)){
            QueryResults<GeneralExtractRelationEntity> results=queryRelationById(taskId,pageRequest);
            List<GeneralExtractRelationEntity> list=results.getResults();
            List<GeneralExtractVo> listRrcord=new ArrayList<>();
            for (GeneralExtractRelationEntity entity:list) {
                Generecord generecord=generecordService.queryById(entity.getGeneralId());
                GeneralExtractVo generalExtractVo =new GeneralExtractVo();
                generalExtractVo.setLinkId(entity.getGeneralId());
                generalExtractVo.setTaskId(entity.getTaskId());
                generalExtractVo.setCqStatus(entity.getCqStatus());
                generalExtractVo.setCheckOrg(generecord.getCheckOrg());
                generalExtractVo.setProAddress(generecord.getProAddress());
                generalExtractVo.setIndustry(generecord.getIndustry());
                generalExtractVo.setCheckStatus(generecord.getCheckStatus());
                generalExtractVo.setOrgLevel(generecord.getOrgLevel());
                generalExtractVo.setUnitName(generecord.getUnitName());
                generalExtractVo.setUnitCode(generecord.getUnitCode());
                generalExtractVo.setUnitLegal(generecord.getUnitLegal());
                generalExtractVo.setUnitPhone(generecord.getUnitPhone());
                generalExtractVo.setUnitUser(generecord.getUnitUser());
                generalExtractVo.setCheckUser(generecord.getCheckUser());
                generalExtractVo.setCheckView(generecord.getCheckView());
                generalExtractVo.setCreateUserType(generecord.getCreateUserType());
                generalExtractVo.setEarthquakeAttach(generecord.getEarthquakeAttach());
                generalExtractVo.setNoticeStatus(generecord.getNoticeStatus());
                generalExtractVo.setProName(generecord.getProName());
                generalExtractVo.setReId(generecord.getReId());
                generalExtractVo.setIndustry(generecord.getIndustry());
                generalExtractVo.setReportStatus(generecord.getReportStatus());
                generalExtractVo.setReCreateUser(generecord.getReCreateUser());
                listRrcord.add(generalExtractVo);
            }
            QueryResults<GeneralExtractVo> queryResults=new QueryResults<>(listRrcord,results.getLimit(),results.getOffset(),results.getTotal());
            return queryResults;
        }else {
            return null;
        }

    }

    @Override
    @Transactional
    @Modifying
    public void updExtractLawerRelation(String taskId, String generalId) {
        QGeneralExtractRelationEntity q=QGeneralExtractRelationEntity.generalExtractRelationEntity;
        jpaQueryFactory.update(q)
                .set(q.cqStatus, Constant.EXTRACT)
                .where(q.taskId.eq(taskId),q.generalId.eq(generalId))
                .execute();
    }

    @Override
    public List<GeneralWorkInfoEntity> findByTaskId(String taskId) {
        QGeneralWorkInfoEntity q=QGeneralWorkInfoEntity.generalWorkInfoEntity;
        return jpaQueryFactory.selectFrom(q).where(q.taskId.eq(taskId)).fetch();
    }

    @Override
    @Modifying
    @Transactional
    public void addPulic(ApPublicEntity apPublicEntity, HttpServletRequest request) {
        if(StringUtils.isEmpty(apPublicEntity.getRelationId())){
            throw new RuntimeException("拟制公告失败");
        }
        R r = serviceUtil.getUserInfoByRequest(request);
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            apPublicEntity.setCreateUser(userInfo.getLoginName());
            apPublicEntity.setOrganName(userInfo.getOrgName());
        }
        // 根据此请求路径+RelationId 前端axios获取信息
        //apPublicEntity.setPublicUrl("/dzjap/supersiveController/getById");
        apPublicEntity.setRevokeg(Constant.REVOKE_NO);
        // 设置默认值
        apPublicEntity.setDelFlag(Constant.NO_DELETE);
        apPublicEntity.setCreateTime(new Date());
        apPublicEntity.setInputenTime(new Date());

        // 设置类型11：一般工程抽取，根据此类型前端判断进入哪个页面
        apPublicEntity.setFictionType("11");
        publicDao.save(apPublicEntity);
        //调取待办接口
        ApTodoEntity apTodoEntity = new ApTodoEntity();
        apTodoEntity.setStatus(Constant.STATUSDB);
        apTodoEntity.setCreateTime(new Date());
        apTodoEntity.setDelFlag(Constant.NO_DELETE);
        apTodoEntity.setTitle(apPublicEntity.getTitle()+"公开公告审批");
        apTodoEntity.setLinkId(apPublicEntity.getPublicId());
        //审批员才能看到相应的审批
        apTodoEntity.setStation("地震部门审定人员");
        //去审批页
        apTodoEntity.setUrl("../todolist/publick.html");
        apTodoEntity.setLocation(apPublicEntity.getOrganName());
        apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
        //审批的业务
        apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
        apTodoService.saveDB(apTodoEntity);
        QGeneralWorkInfoEntity q = QGeneralWorkInfoEntity.generalWorkInfoEntity;
        jpaQueryFactory.update(q).set(q.enterpriseNotice,"1").where(q.taskId.eq(apPublicEntity.getRelationId())).execute();
        /*QApSupersiveTaskInfoEntity q=QApSupersiveTaskInfoEntity.apSupersiveTaskInfoEntity;
        jpaQueryFactory.update(q).set(q.enterpriseNotice,"1").where(q.id.eq(apPublicEntity.getRelationId())).execute();*/
    }
}
